//Page Object
import { verifyCode, login } from '../../api/user'
Page({
  data: {
    phone: null,
    verifyCode: '', // 246810
    time: 0,
    phoneErrorMessage: '',
    codeErrorMessage: ''
  },

  async verify() {
    try {
      const res = await verifyCode(this.data.phone)
      console.log(res)
      this.setData({
        time: 10
      })
      let timer = setInterval(()=>{
        this.setData({
          time : this.data.time - 1
        })
        if (this.data.time === 0) {
          clearInterval(timer)
        }
      },1000)
      wx.showToast({
        title: '发送成功',
        icon:'success'
      })
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: error.response.data.message,
        icon: 'error'
      })
    }
    
  },

  // 点击叉号
  goback() {
    wx.navigateBack()
  },

  // 登录
  submit() {
    // const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/
    
  },

  onInput() {
    // 手机号码校验
    const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/
    if (!this.data.phone) {
      this.setData({
        phoneErrorMessage: '手机号不得为空'
      })
    }else if (!phoneReg.test(this.data.phone)) {
      this.setData({
        phoneErrorMessage: '手机号格式有错误'
      })
    }else {
      this.setData({
        phoneErrorMessage: null
      })
    }
  },

  onInput2() {
    if (!this.data.verifyCode) {
      this.setData({
        codeErrorMessage: '验证码不得为空'
      })
    } else if (this.data.verifyCode.length !== 6) {
      this.setData({
        codeErrorMessage: '验证码长度错误'
      })
    }else {
      this.setData({
        codeErrorMessage: null
      })
    }
  },

  async bindsubmit(e) {
    console.log(e);
    try {
      this.onInput()
      this.onInput2()
      if (this.data.phoneErrorMessage === '手机号不得为空') {
        throw new Error('手机号不得为空')
      } else if (this.data.phoneErrorMessage === '手机号格式有错误' ) {
        throw new Error('手机号格式有错误')
      }

      if (this.data.codeErrorMessage === '验证码不得为空' ) {
        throw new Error('验证码不得为空')
      } else if ( this.data.codeErrorMessage === '验证码长度错误' ) {
        throw new Error('验证码长度错误')
      }

      const res1 = await login({
        mobile: this.data.phone,
        code: this.data.verifyCode
      })
      console.log(res1);
      wx.showToast({
        title: '登录成功',
        icon:'success'
      })
      wx.setStorageSync('token', res1.data.token)
      
      wx.switchTab({
        url: '/pages/my/my?token=' + res1.data.token
      })
    } catch (error) {
      console.log(error);
      wx.showToast({
        title: error.message,
        icon: 'error'
      })
    }
  },

  //options(Object)
  onLoad: function(options){
    
  },
  onReady: function(){
    
  },
  onShow: function(){
    
  },
  onHide: function(){

  },
  onUnload: function(){

  },
  onPullDownRefresh: function(){

  },
  onReachBottom: function(){

  },
  onShareAppMessage: function(){

  },
  onPageScroll: function(){

  },
  //item(index,pagePath,text)
  onTabItemTap:function(item){

  }
});